package cn.broadin.app.hotel.component;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.broadin.app.hotel.util.XUtils;

/**
 * 时间显示控件
 */
public class TimePickerView extends BaseView<TimePickerViewData> implements Runnable{

    private volatile boolean refreshDateFlag = false;

    /**
     * 刷新主界面时间
     */
    private static final int MSG_REFRESH_DATE = 1;

    private TextView mTextView;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        public void dispatchMessage(Message msg) {
            switch(msg.what){
                case MSG_REFRESH_DATE:
                    mTextView.setText(msg.obj.toString());
                    break;
            }
        }
    };

    public TimePickerView(Context context, TimePickerViewData data) {
        super(context, data);
    }

    @Override
    public View onCreateView(RelativeLayout rootView) {
        LinearLayout linearLayout = new LinearLayout(getContext());
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);

        mTextView = new TextView(getContext());
        LinearLayout.LayoutParams textViewLayoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        mTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getMeasuredPx(mData.textSize));
        mTextView.setTextColor(Color.parseColor(mData.textColor));
        linearLayout.addView(mTextView, textViewLayoutParams);

        // 刷新计时器
        refreshDateFlag = true;
        new Thread(this).start();
        return linearLayout;
    }

    @Override
    public void onDestroy(){
        refreshDateFlag = false;
    }

    @Override
    public void run() {
        while(refreshDateFlag){
            Message msg = Message.obtain();
            msg.what = MSG_REFRESH_DATE;
            msg.obj = XUtils.getDateInfo();
            mHandler.sendMessage(msg);

            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static TimePickerView newInstance(Context context, JSONObject jsonObject){
        TimePickerViewData data = JSON.toJavaObject(jsonObject, TimePickerViewData.class);
        return newInstance(context, data);
    }

    public static TimePickerView newInstance(Context context, TimePickerViewData data){
        return new TimePickerView(context, data);
    }
}